package com.ycx.furns.service.impl;

import com.ycx.furns.dao.FurnDAO;
import com.ycx.furns.dao.impl.FurnDAOImpl;
import com.ycx.furns.entity.Furn;
import com.ycx.furns.entity.Page;
import com.ycx.furns.service.FurnService;

import java.util.List;

public class FurnServiceImpl implements FurnService {
    FurnDAO furnDAO = new FurnDAOImpl();

    @Override
    public boolean addSales(int id, int count) {
        Furn furn = furnDAO.getFurnById(id);
        if(furn.getStock() > 0){
            return furnDAO.addSalesById(id, count) == 1;
        }
        return false;
    }

    @Override
    public boolean minusSales(int id, int count) {
        return furnDAO.minusSalesById(id, count) == 1;
    }

    @Override
    public List<Furn> queryFurns() {
        return furnDAO.queryFurns();
    }

    @Override
    public boolean addFurn(Furn furn) {

        return furnDAO.addFurn(furn) == 1;
    }

    @Override
    public boolean delFurn(Integer id) {
        return furnDAO.delFurn(id) == 1;
    }

    @Override
    public Furn getFurnById(Integer id) {
        return furnDAO.getFurnById(id);
    }

    @Override
    public boolean updateFurn(Furn furn) {
        return furnDAO.updateFurn(furn) == 1;
    }

    @Override
    public  Page<Furn> getPage(int pageNo, int pageSize) {
        Page<Furn> page = new Page<>();
        page.setPageNo(pageNo);
        page.setPageSize(pageSize);
        int totalRowNum = furnDAO.getTotalRowNum();
        page.setTotalRowNum(totalRowNum);
        int pageTotalNum = totalRowNum / pageSize;
        if(totalRowNum % pageSize > 0){
            pageTotalNum += 1;
        }
        page.setPageTotalNum(pageTotalNum);
        List<Furn> furns = furnDAO.queryFurnsOfLimit(pageNo, pageSize);
        page.setItems(furns);
        return page;
    }

    @Override
    public Page<Furn> getPageByName(String name, int pageNo, int pageSize) {
        Page<Furn> page = new Page<>();
        page.setPageNo(pageNo);
        page.setPageSize(pageSize);
        int totalRowNumByName = furnDAO.getTotalRowNumByName(name);
        page.setPageTotalNum(totalRowNumByName);
        int pageTotalNum = totalRowNumByName / pageSize;
        if(totalRowNumByName % pageSize > 0){
            pageTotalNum += 1;
        }
        page.setPageTotalNum(pageTotalNum);
        List<Furn> furns = furnDAO.queryFurnsOfLimitByName(name, pageNo, pageSize);
        page.setItems(furns);
        return page;
    }


}
